import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { staticRoutes } from "@/router/routes";
import { reqLogin, reqLogout, reqUserInfo } from "@/api/user";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string,
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: "",
      avatar: "",
    },
    menuRoutes: staticRoutes,
  }),

  actions: {
    async login(username: string, password: string) {
      //login是一个异步函数,将来调用这个函数的时候,会确认是否成功,所以默认login返回成功promise,如果在login中发生失败,则应该返回失败的promise
      try {
        const result = await reqLogin({ username, password });
        // console.log(result, 111);

        //设置token本地存储
        setToken(result.token);
        //把token放在state中
        this.token = result.token;
      } catch (e) {
        return Promise.reject(e);
      }
    },

    async getInfo() {
      try {
        const result = await reqUserInfo();
        this.userInfo = result;
      } catch (e) {
        return Promise.reject(e);
      }
    },

    async logout() {
      try {
        //发送退出登录请求
        await reqLogout();
        //调用自己封装的reset方法
        this.reset();
      } catch (e) {
        return Promise.reject(e);
      }
    },

    reset() {
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      //清空userInfo
      this.userInfo = {
        routes: [],
        buttons: [],
        roles: [],
        name: "",
        avatar: "",
      };
    },
  },
});
